package com.antler.smt.utils;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

/**
 * 上传工具类
 *
 * @author vic
 * @date 2018-01-22 11:52
 */
public class FileUtil {

    /**
     * 上传文件
     *
     * @param request 请求
     * @param uploadPath 上传文件路径
     * @return 布尔值
     * @throws Exception 异常
     */
    public static boolean upload(HttpServletRequest request, String uploadPath, List<String> fileNames) throws Exception {
        boolean result = false;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart == true) {
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");
            for (int i = 0; i < files.size(); i++) {
                MultipartFile multipartFile = files.get(i);
                /** 获取文件的后缀* */
                String fileName = multipartFile.getOriginalFilename();
                InputStream inputStream;
                if (fileName != null) {
                    inputStream = multipartFile.getInputStream();
                    String file = uploadPath + fileNames.get(i);
                    // 定义一个文件名字进行接收获取文件
                    FileOutputStream fileOut = new FileOutputStream(new File(file));
                    byte[] buf = new byte[1024 * 8];
                    while (true) {
                        int read = 0;
                        if (inputStream != null) {
                            read = inputStream.read(buf);
                        }
                        if (read == -1) {
                            break;
                        }
                        fileOut.write(buf, 0, read);
                    }
                    // 查看文件获取是否成功
                    if (fileOut.getFD().valid() == true) {
                        result = true;
                        System.out.println("获取文件保存成功");
                    } else {
                        System.out.println("获取文件失败");
                    }
                    fileOut.flush();
                }
            }
        }
        return result;
    }

    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的路径+文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static Boolean deleteFile(String filePath) {
        Boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}
